import { HttpClient, HttpHeaders, HttpParams, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { environment as env } from 'src/environments/environment';
import { Observable } from 'rxjs/internal/Observable';
import { throwError } from 'rxjs/internal/observable/throwError';
import { catchError } from 'rxjs/operators';

const BASE_URL = env.serverUrl;

export interface JsonResult<T> {
  scoreV2: { value: number; name: string; }[];
  status: number;
  data?: T;
  msg?: string;
}

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  private options = { headers: new HttpHeaders().set('Content-Type', 'application/json') };

  constructor(private httpClient: HttpClient) { }

  public get(path: string, options: object = {}): Observable<JsonResult<any> | any> {
    return this.httpClient.get(BASE_URL + path, options).pipe(catchError(this.formatErrors));
  }

  public put(path: string, body: object = {}, options: object = {}): Observable<JsonResult<any> | any> {
    Object.assign(options, this.options);
    return this.httpClient
      .put(BASE_URL + path, JSON.stringify(body), options)
      .pipe(catchError(this.formatErrors));
  }

  public post(path: string, body: object = {}, options: object = {}): Observable<JsonResult<any> | any> {
    Object.assign(options, this.options);
    console.log(options);
    return this.httpClient
      .post(BASE_URL + path, JSON.stringify(body), options)
      .pipe(catchError(this.formatErrors));
  }

  public delete(path: string): Observable<JsonResult<any>> {
    return this.httpClient.delete(BASE_URL + path).pipe(catchError(this.formatErrors));
  }

  private formatErrors(error: any): Observable<any> {
    return throwError(error.error);
  }

  public fileUpLoad(path: string, formData: FormData): Observable<any> {
    return this.httpClient
      .post(BASE_URL + path, formData)
      .pipe(catchError(this.formatErrors));
  }
}
